package com.wxy.config;

import com.wxy.eneity.ConnThreadLocal;
import com.wxy.eneity.MyException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.sql.Connection;
import java.util.Map;

/**
 * @author 47868
 */
public class MyInterceptor implements HandlerInterceptor {
    private static final String FAV ="/favicon.ico";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if(FAV.equals(path)){
            return true;
        }
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            throw new MyException("请先登录...");
        }
        for (Cookie cookie : cookies) {
            if("token".equals(cookie.getName())){
                token = cookie.getValue();
            }
        }
        if(token == null){
            throw new MyException("请先登录1...");
        }
        Map<String,Object> maps = JwtConfig.checkToken(token);
        int id = (int) maps.get("id");
        if(id == 0){
            throw new MyException("请重新登录...");
        }
        ConnThreadLocal.CONN.set(id);
        return true;
    }
}
